<?php
/**
 * @name ErrorController
 * @desc 错误控制器, 在发生未捕获的异常时刻被调用
 * @see http://www.php.net/manual/en/yaf-dispatcher.catchexception.php
 * @author xmwg6125\ccuser
 */
class ErrorController extends \Yaf\Controller_Abstract {

	//从2.1开始, errorAction支持直接通过参数获取异常
	public function errorAction($exception) {
        echo "<pre>";print_r($exception);exit;
        // 获取异常对象
        $exception = $this->getRequest()->getException();
        if ($exception instanceof Yaf\Exception\LoadFailed\Action) {
            $tracyArray = $exception->getTrace();
            $lastTrace = end($tracyArray);
            $exception = $lastTrace['args'][0];
        }
        if (empty($exception)){
            //Fatal error 通常是无法通过常规的 try-catch 块捕获的，因为它们在运行时导致脚本立即终止。然而，通过设置全局的异常和错误处理程序，我们可以捕获大多数类型的错误，包括致命错误。
            $exception = $this->getRequest()->getParam('exception');
        }
        if (!$this->getRequest()->isCli()){
            // 设置JSON响应头和状态码
            $this->getResponse()->setHeader('Content-Type', 'application/json');
            // 设置 JSON 响应头
            header('Content-Type: application/json');

            // 返回JSON响应
            $this->getResponse()->setBody(json_encode([
                'code' => 500,
                'exception' => [
                    'message' => $exception->getMessage(),
                    'file' => $exception->getFile(),
                    'line' => $exception->getLine(),
                    'trace' => explode("\n", $exception->getTraceAsString())
                ]
            ]));
        }else{
            echo "<pre>";print_r([
                'message' => $exception->getMessage(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
                'trace' => explode("\n", $exception->getTraceAsString())
            ]);
        }
        $logger = \Yaf\Registry::get('logger');
        $logger->info($this->getRequest()->getServer('User-Agent'));
        $logger->error('异常信息', [
            'message' => $exception->getMessage(),
            'file' => $exception->getFile(),
            'line' => $exception->getLine(),
            'trace' => explode("\n", $exception->getTraceAsString())
        ]);
        return false; // 停止自动渲染视图
	}
}
